const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const fs = require("fs");
const path = require("path");

const preloadpath = path.join(__dirname, "preload.cjs");

function createWindow() {
  let mainWin = new BrowserWindow({
    width: 600,
    height: 600,
    minHeight: 600,
    minWidth: 600,
    show: false,
    webPreferences: {
      sandbox: false,
      preload: preloadpath,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
    },
  });

  ipcMain.handle("create-file", async () => {
    try {
      const result = await choosefile();
      return result;
    } catch (error) {
      console.error("Failed to choose file: ", error);
      return null; // 或者其他适当的错误处理
    }
  });

  function choosefile() {
    return new Promise((resolve, reject) => {
      dialog
        .showOpenDialog({
          properties: ["openFile", "multiSelections"],
        })
        .then((result) => {
          if (result.filePaths) {
            fs.readFile(result.filePaths[0], (err, data) => {
              if (err) {
                console.log(err);
              } else {
                const url = "data:video/mp4;base64," + data.toString("base64");
                resolve(url);
              }
            });
          } else {
            reject(new Error("No file path selected"));
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  if (process.env.NODE_ENV == "production") {
    console.log(111);
    mainWin.loadURL(`file://${path.join(__dirname, "../dist/index.html")}`);
  } else {
    mainWin.loadURL("http://localhost:5173/");
  }

  mainWin.on("ready-to-show", () => {
    mainWin.show();
    // console.log(preloadpath);
  });
  mainWin.on("v-fs", () => {
    console.log(1111115454545);
  });
}

app.whenReady().then(() => {
  createWindow();
});

app.on("window-all-closed", () => {
  if (process.platform != "darwin") app.quit();
});
